package xiangmu.schoolpaper.utils;

import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import xiangmu.schoolpaper.pojo.entity.OperateLog;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

public class ExcelWriterUtil {

    // 私有构造方法，防止实例化
//    private ExcelWriterUtil() {}

    public static void writeExcel(HttpServletResponse response,
                                  List<OperateLog> adminList) throws Exception {
        // 1. 构建writer对象
        ExcelWriter writer = ExcelUtil.getWriter(true);    // 参数true，是否为xlsx格式
        // 2. 设置表头,第一个参数是实体类的属性名，第二个参数是excel文件中要呈现的列名
        writer.addHeaderAlias("operateId", "操作人的ID");
        writer.addHeaderAlias("operateTime", "操作时间");
        writer.addHeaderAlias("className", "类名");
        writer.addHeaderAlias("methodName", "方法名");
        writer.addHeaderAlias("methodParams", "方法参数");
        writer.addHeaderAlias("returnValue", "返回值");
        writer.addHeaderAlias("costTime", "耗时");
//        writer.addHeaderAlias("createdTime", "创建时间");
        writer.addHeaderAlias("id", "id");

        // 在写excel文件时只写上面设置了别名的属性
        writer.setOnlyAlias(true);
        // 4. 将数据写入，第二个参数：是否强制写标题
        writer.write(adminList, true);
        // 5. 设置响应类型和响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("日志信息", StandardCharsets.UTF_8);
        response.setHeader("Content-Disposition",
                "attachment;filename=" + fileName + ".xlsx");
        // 6. 写出到流并关闭
        try (ServletOutputStream out = response.getOutputStream()) {
            writer.flush(out, true);
        } finally {
            writer.close();// 关闭writer，释放内存
        }
    }

}